package UI.Scrollbar
{
	import Events.*;
	
	import UI.Buttons.*;
	
	import flash.display.*;
	import flash.events.MouseEvent;
	import flash.geom.*;
	
	import mx.core.UIComponent;
	
	public class UIScrollbar extends UIComponent
	{
		private const WIDTH:Number = 15;
		private const ARROW_COLOR:uint = uint(0xfff000);
		private const TRACK_COLOR:uint = uint(0xffa000);;
		private const SCROLL_UNITS:int = 25;
		
		private var upArrow:UIButton;
		private var downArrow:UIButton;
		private var track:UIButton;
		
		public function UIScrollbar()
		{
			super();
			upArrow = new UIButton(new Bitmap(new BitmapData(WIDTH,WIDTH,false,ARROW_COLOR)));
			downArrow = new UIButton(new Bitmap(new BitmapData(WIDTH,WIDTH,false,ARROW_COLOR)));
			track = new UIButton(new Bitmap(new BitmapData(WIDTH,1,false,TRACK_COLOR)));
			height=upArrow.height+downArrow.height+track.height;
			
			addEventListeners();
			addChildren();
			positionElements();
		}
		
		private function addEventListeners():void
		{
			upArrow.addEventListener(MouseEvent.CLICK,scrollUp);
			downArrow.addEventListener(MouseEvent.CLICK,scrollDown);
		}
		
		private function scrollUp(e:MouseEvent):void
		{
			track.y-=Math.max(0,Math.min(SCROLL_UNITS,track.y-upArrow.height));
			dispatchEvent(new UIScrollbarEvent(UIScrollbarEvent.SCROLL));
		}
		
		private function scrollDown(e:MouseEvent):void
		{
			track.y+=Math.max(0,Math.min(SCROLL_UNITS,downArrow.y-(track.y+track.height)));
			dispatchEvent(new UIScrollbarEvent(UIScrollbarEvent.SCROLL));
		}
		
		private function addChildren():void
		{
			addChild(track);
			addChild(upArrow);
			addChild(downArrow);
		}
		
		private function positionElements():void
		{
			track.y = upArrow.height;
			downArrow.y = height-downArrow.height;
		}
		
		public function get trackPositionToScrollAreaRatio():Number
		{
			return (track.y-upArrow.height)/(height-upArrow.height-downArrow.height);
		}
		
		public function set trackScale(scale:Number):void
		{
			scale=Math.min(scale,1);
			track.height=(height-(downArrow.height+upArrow.height))*scale;
			positionElements();
		}
		
		public function get trackScale():Number
		{
			return track.height/(height-(downArrow.height+upArrow.height));
		}
		
		public override function set height(h:Number):void
		{
			var tScale:Number = trackScale;
			super.height=h;
			trackScale = tScale;
			positionElements();
		}
		
		public override function get width():Number
		{
			return track.width;
		}
	}
}